package nio;

import org.junit.Test;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.Pipe;

/**
 * @author lzy
 * @version v1.0
 * Create DateTime: 2018/8/25 20:30
 */
public class PipeTest {

    @Test
    public void testPipe1() {
        //1.获取管道
        Pipe pipe = null;
        try {
            pipe = Pipe.open();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //2.将缓冲区的数据写入管道
        try (Pipe.SinkChannel sinkChannel = pipe.sink();
             Pipe.SourceChannel sourceChannel = pipe.source()) {
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            buffer.put("通过单向管道发送数据".getBytes());
            buffer.flip();
            sinkChannel.write(buffer);

            //3.从缓冲区中读取数据
            buffer.flip();
            int len = sourceChannel.read(buffer);
            System.out.println(new String(buffer.array(), 0, len));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
